import {loadNewsDetail ,userlike} from '../../http/api'
// pages/news/news.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    news: {},
    isLiked: false,
    userId:'',
  },
    
  navigateBack: function () {
    wx.navigateBack({
      delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页。
    });
  },

  onLoad(options) {
    const newsId = options.itemId;
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userId:userInfo.userId
    })
    this.loadNews(newsId);
  },
  loadNews(newsId) {
    wx.showLoading();
    const userId = this.data.userId;
    loadNewsDetail(newsId,userId)
      .then(res => {
        if (res.success) {
          let newsData = res.data;
          if (newsData.images && Array.isArray(newsData.images)) {
            newsData.images = newsData.images.map(image => 
              `https://wechatobject-1355794559.cos.ap-guangzhou.myqcloud.com/food/${image}`
            );
          }
          this.setData({
            news: res.data,
            isLiked: res.data.isLiked
          });
          wx.showToast({
            title: '加载完成',
          })

        }
    })
  },
  toggleLike() {
    const { news, isLiked } = this.data;
    const newCommentCount = isLiked ? news.commentCount - 1 : news.commentCount + 1;
    const userId = this.data.userId;
    wx.showLoading();
    userlike(isLiked,news.newsId, userId)
      .then(res => {
        if (res.success) {
          wx.showToast({
            title: '操作完成',
          })          
          this.setData({
            isLiked: !isLiked,
            'news.commentCount': newCommentCount
          });
        }
      })
  }

})